//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')

// 数据库-集合account中创建一个记录，然后复制id替换
var dbName = "bf55b7265f257df500016ef860358507";

Page({
  data: {},

  onLoad: function () {
    //获取数据库信息 
    this.updateInfo()
  },


  updateInfo: function () {
    wx.cloud.init()
    const db = wx.cloud.database()
    db.collection('account').doc(dbName).get().then(res => {
      this.setData({
        Balance: res.data.Balance,
        Coins: res.data.Coins,
        startPrice: res.data.startPrice, //基价
        startCointNums: res.data.startCointNums, //一直持币的价值
        rate: res.data.AllProfit ? this.adjustFloat(res.data.AllProfit / res.data.startBalance * 100, 3) + "%" : "0%", //收益率
        buyPriceList: res.data.buyPriceList, //买入的价格和数量
        AllRate: res.data.AllRate ? this.adjustFloat(res.data.AllRate, 3) : '0', //所有手续费
        AllProfit: res.data.AllProfit ? this.adjustFloat(res.data.AllProfit, 3) : '0', //所有利润
        tradeID: res.data.tradeID,
        targetBuyPrice: res.data.targetBuyPrice,
        targetSellPrice: res.data.targetSellPrice,
        sellPrice: res.data.sellPrice,
        buyPrice: res.data.buyPrice,
        time: util.formatTime(res.data.time)
      })

    })



    // 获取前20条交易记录
    db.collection('trade').orderBy('time', 'desc').get().then(res => {
      console.log(res.data)
      res.data.forEach((item) => {
        item.time = util.formatTime(item.time)
      })
      this.setData({
        tradeList: res.data
      })

      wx.stopPullDownRefresh({
        complete: (res) => {},
      })

    })

  },


  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    this.updateInfo()
  },



  /**
   * 订阅消息
   */
  submessage: function () {
    wx.requestSubscribeMessage({
      tmplIds: ['HhgWb5Si9L7iMJBWQS9rLWyOo-nv56TaE1u7CO3f6Wo'], // 模版ID，小程序后台订阅消息-复制模版ID
      success(res) {
        console.log("订阅：" + res)
        wx.showToast({
          icon: "none",
          title: '订阅成功',
        })
      },
    })
  },

  //保留小数点后三位
  adjustFloat: function (num, length) {
    return Math.floor(num * Math.pow(10, length)) / Math.pow(10, length);
  },



})